#!/bin/bash

# lock_users.sh
# 功能说明:
# 1. 锁定指定用户账户，禁止登录系统。
# 2. 支持通过命令行传入用户名，或从文件读取用户名列表（兼容 create_users.sh 的文件格式）。

# 锁定用户账户
lock_user() {
  local username="$1"

  if id "$username" &>/dev/null; then
    sudo usermod -L "$username" 2>/dev/null
    if [[ $? -eq 0 ]]; then
      echo "User $username has been locked."
    else
      echo "Failed to lock user $username."
    fi
  else
    echo "User $username does not exist. Skipping..."
  fi
}

# 从文件批量锁定用户
process_file() {
  local file="$1"

  if [[ ! -f "$file" ]]; then
    echo "File $file does not exist. Please provide a valid file."
    exit 1
  fi

  while IFS= read -r line; do
    [[ -z "$line" || "$line" == \#* ]] && continue

    # 提取用户名，忽略密码部分
    local username=$(echo "$line" | awk '{print $1}')
    lock_user "$username"
  done <"$file"
}

# 主函数
main() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [username | -f user_file]"
    echo "  username: Specify a single user to lock."
    echo "  -f user_file: Specify a file containing usernames to lock."
    exit 1
  fi

  if [[ "$1" == "-f" ]]; then
    shift
    if [[ -n "$1" ]]; then
      process_file "$1"
    else
      echo "Error: Missing file name after -f."
      exit 1
    fi
  else
    lock_user "$1"
  fi
}

# 执行主函数
main "$@"

